
#include <stdio.h>
#include <iostream>
#include "AuditPlanFun.h"
#include <string>
#include <time.h>
#include <sys/types.h>
//#include <ifaddrs.h>
//#include <netinet/in.h>
#include <string.h>
//#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
//#include <net/if.h>
//#include <arpa/inet.h>
//#include <sys/ioctl.h>
//#include <sys/socket.h>
#include <error.h>
//#include "GenKey/SqlUtil.h"
#include <vector>
#include <iostream>
#include <fstream>
#include <dirent.h>
#include "curl.h"
//#include "Core/CoreBase.h"
#include <unistd.h>
#include <sys/types.h>
#include <QNetworkInterface>
#include <QJsonDocument>
#include <QJsonObject>
#include <QList>
#include <QFile>
#include <QTextStream>
#include <QStorageInfo>
#include "UsbIO.h"
#include "ferryfs.h"
//#include <pwd.h>
const char *username = std::getenv("USER");


// #include "MyDB.h"
using namespace std;
using namespace UsbEncrypt;



bool AuditFun::isRemovableDrive(const QString &drivePath)
{
    UINT driveType = GetDriveType(reinterpret_cast<const TCHAR*>(drivePath.utf16()));
    return driveType == DRIVE_REMOVABLE;
}



//windows
AuditFun::AuditFun(QString drivePath){
    usbPath = drivePath.toStdString();
    std::cout << "--windows--------the usb path is--------" << std::endl
              << usbPath << std::endl;

}

AuditFun::AuditFun()
{

        QList<QStorageInfo> storageList = QStorageInfo::mountedVolumes();

        // 遍历存储设备列表
        foreach (const QStorageInfo &storage, storageList) {
            // 判断设备是否为可移动设备
            if (storage.isValid() && storage.isReady()) {
                QString drivePath = storage.rootPath();
                if (isRemovableDrive(drivePath)) {
                    this->usbPath = drivePath.toStdString();

                }
            }
        }


}


//linux
//AuditFun::AuditFun(){
//    DIR *dir;
//    struct dirent *entry;
//    // std::string usbPath;
//    string path =
//    // dir = opendir("/media/内容/" + std::string(username)).c_str());
//    dir = opendir("G:/");
//    if (dir == nullptr)
//    {
//        std::cout << "can not open directorty" << std::endl;
//    }

//    //uid_t uid = getuid();  // 获取当前进程的有效用户 ID

//    // struct passwd* pw = getpwuid(uid);
//    // std::string Username = pw->pw_name;
//    //     std::cout << "当前非 root 用户名：" << Username << std::endl;

//    while ((entry = readdir(dir)) != nullptr)
//    {
//        //if (entry->d_type == DT_DIR && std::string(entry->d_name) != "." && std::string(entry->d_name) != "..")

//        if (std::string(entry->d_name) != "." && std::string(entry->d_name) != "..")
//        {

//            // usbPath = "/media/" + std::string(username) + "/" + std::string(entry->d_name);
//            std::string usbname = std::string(entry->d_name);
//            std::cout << "------------usbname is--------" << std::endl
//                      << usbname << std::endl;

//            //std::string Username = std::string(username);
//            //std::cout << "------------Username is--------" << std::endl
//            //          << Username << std::endl;
                      
//            // if (usbname != Username && usbname != "root" && usbname != "user" )
//            // if (usbname != "root" && usbname != "user" )
//            // {
//            //     /* code */
//            //     usbPath = "F:/" + usbname;
//            //     std::cout << "------------the usb path is--------" << std::endl
//            //               << usbPath << std::endl;
//            //     break;
//            // }

//                usbPath = "F:/" ;
//                std::cout << "------------the usb path is--------" << std::endl
//                          << usbPath << std::endl;
//                break;
//        }
//    }
//    // sleep(2);
//    // string str(path.begin(), path.end());
//    // usbPath = str;
//    // std::cout << "------------usb的路径是--------" << std::endl
//    //           << usbPath << std::endl;

//    closedir(dir);
//    if (usbPath.empty())
//    {
//        std::cout << "unable to find the u disk\n";
//    }

//}

// sqlite回调函数
static int callback(void *NotUsed, int argc, char **argv, char **azColName)
{
    int i;
    for (i = 0; i < argc; i++)
    {
        printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
    }
    printf("\n");
    return 0;
}

// sqlite初始化文件移动函数
void AuditFun::MoveFilesToUSB(const std::vector<std::string> &filePaths, const std::string &usbPath)
{
    for (const auto &filePath : filePaths)
    {
        std::string fullPath;
        const char *pwdpath = __FILE__;
        std::string Pwdpath = pwdpath;
        //size_t lastSeparatorPos = Pwdpath.find_last_of('/');
	  std::string directoryPath = "home/ubuntu/Downloads/usbencrypt1123zhuceji1129/usbencrypt1123zhuceji/src/Main";
        //if (lastSeparatorPos != std::string::npos)
        //{
            //std::string directoryPath = Pwdpath.substr(0, lastSeparatorPos);
            // 拼接文件路径
            //fullPath = directoryPath + "/" + filePath;
        //}
        fullPath = directoryPath + "/" + filePath;
        std::ifstream sourceFile(fullPath, std::ios::binary);
        if (!sourceFile)
        {
            std::cout << "无法打开源文件" << fullPath << std::endl;
            continue;
        }
        size_t lastSlashIndex = fullPath.find_last_of("/\\");
        std::string filename = fullPath.substr(lastSlashIndex + 1);
        std::string destinationPath = usbPath + "/" + filename;
        std::cout << destinationPath << "------------------" << std::endl;
        std::ofstream destinationFile(destinationPath, std::ios::binary);

        if (!destinationFile)
        {
            std::cout << "无法打开目的文件" << usbPath << std::endl;
            continue;
        }

        destinationFile << sourceFile.rdbuf();
        std::cout << "成功移动文件: " << fullPath << " 到: " << usbPath << std::endl;
    }
    std::cout << "所有文件成功移动到U盘中\n";
}

// sqlite初始化函数
bool AuditFun::InitializeSQL()
{

    // DIR *dir;
    // struct dirent *entry;
    // // std::string usbPath;

    // // dir = opendir("/media/内容/" + std::string(username)).c_str());
    // dir = opendir("/media/");
    // if (dir == nullptr)
    // {
    //     std::cout << "无法打开目录" << std::endl;
    //     return false;
    // }

    //  uid_t uid = getuid();  // 获取当前进程的有效用户 ID

    // // struct passwd* pw = getpwuid(uid);
    // // std::string Username = pw->pw_name;
    // //     std::cout << "当前非 root 用户名：" << Username << std::endl;

    // while ((entry = readdir(dir)) != nullptr)
    // {
    //     if (entry->d_type == DT_DIR && std::string(entry->d_name) != "." && std::string(entry->d_name) != "..")
    //     {

    //         // usbPath = "/media/" + std::string(username) + "/" + std::string(entry->d_name);
    //         std::string usbname = std::string(entry->d_name);
    //         std::cout << "------------usbname是--------" << std::endl
    //                   << usbname << std::endl;

    //         std::string Username = std::string(username);
    //         std::cout << "------------Username是--------" << std::endl
    //                   << Username << std::endl;
                      
    //         if (usbname != Username && usbname != "root" )
    //         {
    //             /* code */
    //             usbPath = "/media/" + usbname;
    //             std::cout << "------------usb的路径是--------" << std::endl
    //                       << usbPath << std::endl;
    //             break;
    //         }
    //     }
    // }    
    // // sleep(2);
    // // string str(path.begin(), path.end());
    // // usbPath = str;
    // // std::cout << "------------usb的路径是--------" << std::endl
    // //           << usbPath << std::endl;

    // closedir(dir);
    // if (usbPath.empty())
    // {
    //     std::cout << "未找到插入的U盘\n";
    //     return false;
    // }

    // 要移动的文件路径列表
    std::vector<std::string> filePaths = {
        "sqldiff",
        "sqlite3",
        "sqlite3_analyzer"};
    std::string predbPath = usbPath + "/test.db";
    std::ifstream checkFile(predbPath);
    if (checkFile)
    {
        std::cout << "U盘中已存在test.db文件" << std::endl;
    }
    else
    {
        filePaths.push_back("test.db");
    }
    MoveFilesToUSB(filePaths, usbPath);
    std::cout << "sqlite初始化成功\n";
    return true;
}

// 判断u盘是否已进行初始化
bool AuditFun::IfInitializeSQL()
{
    std::string lastdbPath = usbPath + "/test.db";
    std::ifstream checkFile(lastdbPath);
    if (checkFile)
    {
        std::cout << "U盘已经初始化" << std::endl;
        return true;
    }
    else
    {
        std::cout << "U盘未初始化" << std::endl;
    }
    return false;
}

// 获取日志信息
string AuditFun::getIp()
{
    QString strIpAddress;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    // 获取第一个本主机的IPv4地址
    int nListSize = ipAddressesList.size();
    for (int i = 0; i < nListSize; ++i)
    {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
            ipAddressesList.at(i).toIPv4Address()) {
            strIpAddress = ipAddressesList.at(i).toString();
            break;
        }
    }
    // 如果没有找到，则以本地IP地址为IP
    if (strIpAddress.isEmpty())
        strIpAddress = QHostAddress(QHostAddress::LocalHost).toString();
    string ret = strIpAddress.toStdString();

    return ret;


}
string AuditFun::getMac()
{
    QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表
    int nCnt = nets.count();
    QString strMacAddr = "";
    for(int i = 0; i < nCnt; i ++)
    {
        // 如果此网络接口被激活并且正在运行并且不是回环地址，则就是我们需要找的Mac地址
        if(nets[i].flags().testFlag(QNetworkInterface::IsUp) && nets[i].flags().testFlag(QNetworkInterface::IsRunning) && !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack))
        {
            strMacAddr = nets[i].hardwareAddress();
            break;
        }
    }
    string ret = strMacAddr.toStdString();

    return ret;
}
string AuditFun::getTime()
{
    time_t timep;
    time(&timep);
    char tmp[64];
    strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S", localtime(&timep));
    std::cout << "tmp:" << tmp << std::endl;
    return tmp;
}

// sqlite插入原始的审计信息
bool AuditFun::insertAuditInfo()
{

//     sqlite3 *db;
//     char *zErrMsg = 0;
//     int rc;
//     const char *sql;

//     string macIp, insertionTime, computerIp, usbnumber, lastreadtime, lastwritetime, removaltime, installedsp, deptid, nickname, departmentname, areaname;
//     string readcount, writecount, areaid, userid;

//     insertionTime = this->getTime();
//     usbnumber = "E000002";
//     readcount = "1";
//     writecount = "1";
//     lastreadtime = insertionTime;
//     lastwritetime = insertionTime;
//     areaid = "1";
//     userid = "1";
//     removaltime = insertionTime;
//     installedsp = "1";
//     deptid = "205";
//     nickname = "若依";
//     departmentname = "城阳";
//     areaname = "青岛单位";

//     macIp = this->getMac();

//     computerIp = this->getIp();

//     // open database
//     std::string dbPath = usbPath + "test.db";
//     std::cout << "*************the db path is*************" << dbPath << ::endl;
//     /* Open database */
//     rc = sqlite3_open(dbPath.c_str(), &db);

//     if (rc)
//     {
//         fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
//         exit(0);
//     }
//     else
//     {
//         //fprintf(stderr, "Opened database successfully\n");
//         std::cout << "Opened database successfully" << std::endl;
//     }
// // create sql statement
// std:
//     string sqlstatement = "insert into eu_usb_info (usb_number,readCount,writeCount,lastReadTime,lastWriteTime,area_id,user_id,insertionTime,removalTime,computerIp,installedSP,dept_id,macIp,nick_name,department_name,area_name) values('" + usbnumber + "','" + readcount + "','" + writecount + "','" + lastreadtime + "','" + lastwritetime + "','" + areaid + "','" + userid + "','" + insertionTime + "','" + removaltime + "','" + computerIp + "','" + installedsp + "','" + deptid + "','" + macIp + "','" + nickname + "','" + departmentname + "','" + areaname + "');";
//     sql = sqlstatement.c_str();

//     // execute sql statement
//     rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
//     if (rc != SQLITE_OK)
//     {
//         fprintf(stderr, "SQL error: %s\n", zErrMsg);
//         sqlite3_free(zErrMsg);
//     }
//     else
//     {
//         //fprintf(stdout, "Records created successfully\n");
//         std::cout << "Records created successfully\n" << std::endl;
//     }
//     sqlite3_close(db);
//     return 0;
}

// sqlite插入u盘使用日志信息
bool AuditFun::insertUseInfo(string File_name, string Operate_type, string Operate_time, string Usb_id)
{
//     sqlite3 *db;
//     char *zErrMsg = 0;
//     int rc;
//     const char *sql;

//     string file_name = File_name;
//     string operate_type = Operate_type;
//     string operate_time = Operate_time;
//     string usb_id = Usb_id;
//     // open database
//     std::string dbPath = usbPath + "/test.db";
//     std::cout << "*************the db path is*****************" << dbPath << ::endl;
//     /* Open database */
//     rc = sqlite3_open(dbPath.c_str(), &db);
//     if (rc)
//     {
//         fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
//         exit(0);
//     }
//     else
//     {
//         fprintf(stderr, "Opened database successfully\n");
//     }
//     string sqlstatement = "insert into operate_log (file_name,operate_type,operate_time,usb_id) values ('" + file_name + "','" + operate_type + "','" + operate_time + "','" + usb_id + "');";
//     sql = sqlstatement.c_str();
//     // execute sql statement
//     rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
//     if (rc != SQLITE_OK)
//     {
//         fprintf(stderr, "SQL error: %s\n", zErrMsg);
//         sqlite3_free(zErrMsg);
//     }
//     else
//     {
//         fprintf(stdout, "Records created successfully\n");
//     }
//     sqlite3_close(db);
//     return true;
}

// 把审计信息发送给后端接口
size_t write_callback(void *contents, size_t size, size_t nmemb, void *userip)
{
    size_t total_size = size * nmemb;
    printf("%s", (char *)contents);
    return total_size;
}

size_t getLoginData(void *contents, size_t size, size_t nmemb, void *response)
{


    string *str = (string*)response;
    (*str).append((char*)contents,size*nmemb);

    return size*nmemb;
}

#include <QCoreApplication>

QString getIpAddress()
{
    QString ip = "127.0.0.1";
    QString appPath  = QCoreApplication::applicationFilePath();
    appPath.replace("Upan2.exe", "ip.txt");
    QFile file(appPath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "无法打开文件";

    }
    QTextStream in(&file);
    while (!in.atEnd())
    {
        ip = in.readLine();  // 逐行读取数据
        qDebug() << ip;
    }
    return ip;
    file.close();
}

bool postUrl(const char *json)
{
     // CURL *curl;
     // CURLcode res;
     // QString ipaddress = getIpAddress();
     // QString url = "http://" + ipaddress + "/system/usbInfo";
     // qDebug() <<"============" <<url;
     // string urlstr = url.toStdString();
     // curl = curl_easy_init();
     // if (curl)
     // {
     //     struct curl_slist *headers = NULL;
     //     headers = curl_slist_append(headers, "Content-Type: application/json");

     //     curl_easy_setopt(curl, CURLOPT_POST, 1L);

     //     curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
     //     curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json);
     //     curl_easy_setopt(curl, CURLOPT_URL, urlstr.c_str()); // 替换为您要发送请求的URL

     //     curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);

     //     res = curl_easy_perform(curl);
     //     if (res != CURLE_OK)
     //     {
     //         fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
     //         curl_easy_cleanup(curl);
     //         return false;
     //     }

     //     curl_easy_cleanup(curl);
     // }

     // return true;
}

int Callback(void *data, int argc, char **argv, char **azColName)
{
    char json[1024];

    std::string usbNumber = argv[1] ? std::string(argv[1]) : "";
    int readCount = argv[2] ? std::atoi(argv[2]) : 0;
    int writeCount = argv[3] ? std::atoi(argv[3]) : 0;
    std::string lastReadTime = argv[4] ? std::string(argv[4]) : "";
    std::string lastWriteTime = argv[5] ? std::string(argv[5]) : "";
    int areaId = argv[6] ? std::atoi(argv[6]) : 0;
    int userId = argv[7] ? std::atoi(argv[7]) : 0;
    std::string areaName = argv[16] ? std::string(argv[16]) : "";
    std::string insertionTime = argv[8] ? std::string(argv[8]) : "";
    std::string removalTime = argv[9] ? std::string(argv[9]) : "";
    std::string computerIp = argv[10] ? std::string(argv[10]) : "";
    std::string macIp = argv[13] ? std::string(argv[13]) : "";
    int installedSP = argv[11] ? std::atoi(argv[11]) : 0;
    int deptId = argv[12] ? std::atoi(argv[12]) : 0;
    std::string deptName = argv[14] ? std::string(argv[14]) : "";

    snprintf(json, sizeof(json),
             "{\"usbNumber\":\"%s\",\"readCount\":%d,\"writeCount\":%d,\"lastReadTime\":\"%s\",\"lastWriteTime\":\"%s\",\"areaId\":%d,\"userId\":%d,\"areaName\":\"%s\",\"insertionTime\":\"%s\",\"removalTime\":\"%s\",\"computerIp\":\"%s\",\"macIp\":\"%s\",\"installedSP\":%d,\"deptId\":%d,\"deptName\":\"%s\"}",
             usbNumber.c_str(), readCount, writeCount, lastReadTime.c_str(), lastWriteTime.c_str(), areaId, userId, areaName.c_str(), insertionTime.c_str(), removalTime.c_str(), computerIp.c_str(), macIp.c_str(), installedSP, deptId, deptName.c_str());

    std::cout << "挂载的JSON" << json << endl;

//    fstream fs;
//    fs.open(usbPath + "/data.json",ios::out|ios::app);
//    fs << json << endl;
//    fs.close();

    if (postUrl(json))
    {
        printf("JSON: %s\n", json);
        printf("POST request sent successfully.\n");
    }
    else
    {
        printf("Failed to send POST request.\n");
    }

    return 0;
}
bool AuditFun::PostAuditInfo()
{
    // sqlite3 *db;
    // char *zErrMsg = 0;
    // char *err_msg = 0;
    // std::string dbPath = usbPath + "test.db";
    // int rc = sqlite3_open(dbPath.c_str(), &db); // 替换为您的数据库文件名
    // if (rc != SQLITE_OK)
    // {
    //     fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
    //     sqlite3_close(db);
    //     return false;
    // }
    // else
    // {
    //     std::cout << "dbPath:" << dbPath << endl << "open the database successfully" << endl;
    // }


    // const char *sql = "SELECT * FROM eu_usb_info"; // 替换为您的表名
    // //清空json
    // fstream fs;
    // fs.open(usbPath + "/data.json",ios_base::out);
    // fs.close();

    // rc = sqlite3_exec(db, sql, Callback, 0, &err_msg);
    // if (rc != SQLITE_OK)
    // {
    //     fprintf(stderr, "SQL error: %s\n", err_msg);
    //     sqlite3_free(err_msg);
    //     sqlite3_close(db);
    //     return false;
    // }
    // sqlite3_close(db);
    // return true;
}



bool AuditFun::deleteTableInfo()
{


//     sqlite3 *db;
//     char *zErrMsg = 0;
//     int rc;
//     const char *sql;

//     // open database
//     std::string dbPath = usbPath + "test.db";
//     std::cout << "in del*************the db path is*************" << dbPath << ::endl;
//     /* Open database */
//     rc = sqlite3_open(dbPath.c_str(), &db);

//     if (rc)
//     {
//         fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
//         exit(0);
//     }
//     else
//     {
//         //fprintf(stderr, "Opened database successfully\n");
//         std::cout << "Opened database successfully" << std::endl;
//     }
// // create sql statement
// std:
//     string sqlstatement = "delete from eu_usb_info";
//     sql = sqlstatement.c_str();

//     // execute sql statement
//     rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
//     if (rc != SQLITE_OK)
//     {
//         //fprintf(stderr, "SQL error: %s\n", zErrMsg);
//         std::cout << "SQL error:" << zErrMsg << std::endl;
//         sqlite3_free(zErrMsg);
//     }
//     else
//     {
//         //fprintf(stdout, "Records created successfully\n");
//         std::cout << "Records deleted successfully\n" << std::endl;
//     }
//     sqlite3_close(db);
//     return 0;
}

//从json格式中提取值
QJsonObject getValueFromJson(const QString &jsonString)
{
    // 将 QString 转换为 QByteArray
    QByteArray jsonData = jsonString.toUtf8();

    // 解析 JSON 文档
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData);

    // 检查是否成功解析 JSON
    if (jsonDoc.isNull() || !jsonDoc.isObject()) {
        qWarning() << "Failed to parse JSON or JSON is not an object";
        return QJsonObject(); // 或者其他表示错误的值
    }

    // 获取 JSON 对象
    QJsonObject jsonObj = jsonDoc.object();
    return jsonObj;
    // 检查是否包含 "code" 键并且其值是整数类型
//    if (jsonObj.contains("code") && jsonObj["code"].isDouble()) {
//        return jsonObj["code"].toInt();
//    } else {
//        qWarning() << "JSON does not contain 'code' key or 'code' is not an integer";
//        return -1; // 或者其他表示错误的值
//    }
}

//获得json中的code
int getCode(const QString &jsonString){
    QJsonObject jsonObj = getValueFromJson(jsonString);
    if (jsonObj.contains("code") && jsonObj["code"].isDouble()) {
        return jsonObj["code"].toInt();
    } else {
        qWarning() << "JSON does not contain 'code' key or 'code' is not an integer";
        return -1; // 或者其他表示错误的值
    }

}
//获得json中的isEnable
int getIsEnable(const QString &jsonString){
    QJsonObject jsonObj = getValueFromJson(jsonString);
    if (jsonObj.contains("data") && jsonObj["data"].isObject()) {
        QJsonObject dataObj = jsonObj["data"].toObject();
        if (dataObj.contains("isEnable") && dataObj["isEnable"].isDouble()) {
            return dataObj["isEnable"].toInt();
        } else {
            qWarning() << "Response JSON does not contain 'isEnable' key or 'isEnable' is not an integer";
            return false;
        }
    } else {
        qWarning() << "Response JSON does not contain 'data' key or 'data' is not an object";
        return false;
    }

}


bool AuditFun::login(string username, string password){
    CURL *curl = nullptr;
    CURLcode res;
    string response="";
    curl = curl_easy_init();
    QString ipaddress = getIpAddress();
    QString url = "http://" + ipaddress + "/loginUsb";
    if (curl)
    {
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type:application/json");
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
        char json[1024];


        snprintf(json, sizeof(json),
                 "{\"username\":\"%s\",\"password\":\"%s\"}",
                 username.c_str(), password.c_str());
        std::cout << json << endl;


        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json);                             // 指定post内容
        curl_easy_setopt(curl, CURLOPT_URL, url.toStdString().c_str()); // 指定url

        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, getLoginData);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

        res = curl_easy_perform(curl);
        if (res != CURLE_OK)
        {
            std::cout <<"code0:"  << endl;
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
            return false;
        }

        curl_easy_cleanup(curl);
    }

//    string code = response.substr(response.length()-4, 3);
//    std::cout <<"code:" <<code << endl;
//    if(code == "200")return true;


    int code = getCode(QString::fromStdString(response));
    std::cout <<"code:" <<code << endl;
    if(code == 200)return true;
    return false;

}

void AuditFun::getUsbId(string usbPath, stringstream& ss)
{
    UsbIO usbIO(usbPath);
    unsigned char data[16]={0};
    usbIO.ReadPhysicalSector(35, 0, data, 16);
    string usbid;
    // 将每个字节转换为对应的ASCII字符
    //    for (const auto& byte : data) {
    //        usbid += static_cast<unsigned int>(static_cast<unsigned char>(byte));
    //    }

    for (size_t i = 0; i < 16; ++i) {
        ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned int>(static_cast<unsigned char>(data[i]));
    }
    ss << std::dec;
}

QString AuditFun::getConfigIpAddress(){
    return getIpAddress();
}

bool AuditFun::postFileOperation(string filename, int operatetype)
{
    //operatetype 0-create 1-modify 2-delete
    CURL *curl = nullptr;
    CURLcode res;
    string response="";
    curl = curl_easy_init();
    QString ipaddress = getIpAddress();
    ferryfs->connectUdiskDB(QString("ferrylog5"));
    std::string usbNumber = ferryfs->readDeviceIDFromDB().toStdString();
    ferryfs->closeDB();

    qDebug() << "usbPath:" << usbPath;
    //    qDebug() << "usbnumber:" << usbnumber;

    //    std::cout << "Hexadecimal representation of usbnumber:" << std::endl;
    //    for (size_t i = 0; i < usbnumber.size(); ++i) {
    //        std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned int>(static_cast<unsigned char>(usbnumber[i])) << " ";
    //    }
    //    std::cout << std::dec << std::endl;

    string operatetime = getTime();
    QString url = "http://" + ipaddress + "/operateLog/add";
    if (curl)
    {
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type:application/json");
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
        char json[1024];


        snprintf(json, sizeof(json),
                 "{\"fileName\":\"%s\",\"operateTime\":\"%s\",\"operateType\":\"%d\",\"usbNumber\":\"%s\"}",
                 filename.c_str(), operatetime.c_str(), operatetype, usbNumber.c_str());
        std::cout << json << endl;




        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json);                             // 指定post内容
        curl_easy_setopt(curl, CURLOPT_URL, url.toStdString().c_str()); // 指定url

        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, getLoginData);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

        res = curl_easy_perform(curl);
        if (res != CURLE_OK)
        {
            std::cout <<"code0:"  << endl;
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
            return false;
        }

        curl_easy_cleanup(curl);
    }

//    string code = response.substr(response.length()-4, 3);
//    std::cout <<"code:" <<code << endl;
//    if(code == "200")return true;

    int code = getCode(QString::fromStdString(response));
    std::cout <<"code:" <<code << endl;
    if(code == 200)return true;
    return false;

}

bool AuditFun::isUsbEnable(){
    QString usbNumber = ferryfs->readDeviceIDFromDB();
    CURL *curl = nullptr;
    CURLcode res;
    string response="";
    curl = curl_easy_init();
    QString ipaddress = getIpAddress();
    QString url = "http://" + ipaddress + "/system/usbs/getUsbByNumber?number="+usbNumber;
    if (curl) {
        struct curl_slist *headers = nullptr;
        headers = curl_slist_append(headers, "Content-Type:application/json");

        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_URL, url.toStdString().c_str()); // 指定url
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, getLoginData);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
        res = curl_easy_perform(curl);

        if (res != CURLE_OK) {
            std::cout << "code0:" << std::endl;
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
            return false;
        }

        curl_easy_cleanup(curl);
    }
    std::cout << "response:" <<response<< std::endl;

    int isEnable = getIsEnable(QString::fromStdString(response));
    std::cout << "isEnable:" <<isEnable<< std::endl;
    if(isEnable == 1)return true;


    return false;
}

